package com.lagouedu.controller;

import com.aliyun.oss.model.OSSObject;
import com.lagouedu.bean.UploadResult;
import com.lagouedu.service.FileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/oss")
public class FileController {

    @Autowired
    private FileService fileService;

    @RequestMapping("/upload")
    public UploadResult uploadFile(@RequestParam("file") MultipartFile multipartFile){
        return fileService.upload(multipartFile);
    }

    @RequestMapping("/download")
    public void downLoad(String fileName, HttpServletResponse response){

        OSSObject ossObject = fileService.downLoadFile(fileName);
        ServletOutputStream outputStream = null;
        try {
            byte[] bytes = ossObject.getObjectContent().readAllBytes();
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.substringAfterLast(fileName, "/"),"UTF-8"));
            response.setHeader("content-type","image/png");
            response.setCharacterEncoding("UTF-8");
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    @RequestMapping("/delete")
    public Map deleteFile(String fileName){
        Map map = new HashMap();
        if(fileService.deleteFile(fileName)){
            map.put("msg", "success");
            return map;
        }
        map.put("msg","fail");
        return map;
    }
}
